package com.walker.kuyun.ui.activity

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.walker.kuyun.R
import com.walker.kuyun.config.Const
import com.walker.kuyun.databinding.ActivitySettingBinding
import com.walker.kuyun.util.Util.getAppVersionName
import com.walker.kuyun.util.Util.getNightMode
import com.walker.kuyun.util.Util.isNightMode
import com.walker.kuyun.util.Util.setNightMode
import com.walker.kuyun.util.Util.showToast
import com.walker.kuyun.util.Util.showToastOnThread
import com.walker.kuyun.util.gone
import com.walker.kuyun.util.update.AppUpdateHelper
import com.walker.kuyun.util.update.AppUpdateStatus
import com.walker.kuyun.viewmodel.SettingViewModel
import kotlinx.coroutines.*


class SettingActivity : BaseActivity<ActivitySettingBinding>() {
    private val viewModel: SettingViewModel by lazy { ViewModelProvider(this).get(SettingViewModel::class.java) }
    private var selfUpdateCheck = false

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val appUpdateHelper = AppUpdateHelper.instance

        mBinding.run {
            llSettingActivityToolbar.tvToolbar1Title.text = getString(R.string.setting)
            llSettingActivityToolbar.ivToolbar1Back.setOnClickListener { finish() }

            tvSettingActivityDownloadPathInfo.isFocused = true
            tvSettingActivityDownloadPathInfo.text = Const.DownloadAnime.animeFilePath
        }

        // 清理历史记录
        viewModel.mldDeleteAllHistory.observe(this, Observer {
            if (it == null) return@Observer
            if (it) getString(R.string.delete_all_history_succeed).showToast()
            else getString(R.string.delete_all_history_failed).showToast()
            viewModel.mldDeleteAllHistory.postValue(null)
        })
        mBinding.tvSettingActivityDeleteAllHistoryInfo.isFocused = true
        mBinding.rlSettingActivityDeleteAllHistory.setOnClickListener {
            MaterialDialog(this).show {
                icon(R.drawable.ic_delete_main_color_2_24)
                title(res = R.string.warning)
                message(text = "确定要删除所有历史记录？包括搜索历史和观看历史")
                positiveButton(res = R.string.delete) { viewModel.deleteAllHistory() }
                negativeButton(res = R.string.cancel) { dismiss() }
            }
        }

        // 清理缓存文件
        viewModel.mldCacheSize.observe(this, Observer {
            mBinding.tvSettingActivityClearCacheSize.text = it
        })
        viewModel.mldClearAllCache.observe(this, Observer {
            if (it == null) return@Observer
            GlobalScope.launch(Dispatchers.IO) {
                delay(1000)
                viewModel.getCacheSize()
                if (it) getString(R.string.clear_cache_succeed).showToastOnThread()
                else getString(R.string.clear_cache_failed).showToastOnThread()
            }
            viewModel.mldClearAllCache.postValue(null)
        })
        viewModel.getCacheSize()
        mBinding.tvSettingActivityClearCache.isFocused = true
        mBinding.rlSettingActivityClearCache.setOnClickListener {
            MaterialDialog(this).show {
                icon(R.drawable.ic_sd_storage_main_color_2_24)
                title(res = R.string.warning)
                message(text = "确定清理所有缓存？不包括缓存视频")
                positiveButton(res = R.string.clean) { viewModel.clearAllCache() }
                negativeButton(res = R.string.cancel) { dismiss() }
            }
        }

        mBinding.run {
            tvSettingActivityUpdateInfo.text =
                getString(R.string.current_version, getAppVersionName())

            appUpdateHelper.getUpdateServer().observe(this@SettingActivity, Observer {
                tvSettingActivityUpdateInfoServer.text = AppUpdateHelper.serverName[it]
            })
            tvSettingActivityUpdateInfoServer.text =
                AppUpdateHelper.serverName[appUpdateHelper.getUpdateServer().value ?: 0]

            appUpdateHelper.getUpdateStatus().observe(this@SettingActivity, Observer {
                when (it) {
                    AppUpdateStatus.UNCHECK -> {
                        tvSettingActivityUpdateInfo.text = "未检查"
//                    appUpdateHelper.checkUpdate()
                    }
                    AppUpdateStatus.CHECKING -> {
                        tvSettingActivityUpdateTip.text = getString(R.string.checking_update)
                    }
                    AppUpdateStatus.DATED -> {
                        tvSettingActivityUpdateTip.text = getString(R.string.find_new_version)
                        if (selfUpdateCheck) appUpdateHelper.noticeUpdate(this@SettingActivity)
                    }
                    AppUpdateStatus.VALID -> {
                        tvSettingActivityUpdateTip.text = getString(R.string.is_latest_version)
                        if (selfUpdateCheck) getString(R.string.is_latest_version).showToast()
                    }
                    AppUpdateStatus.LATER -> {
                        tvSettingActivityUpdateTip.text = "暂不更新"
                    }
                    AppUpdateStatus.DOWNLOADING -> {
                        tvSettingActivityUpdateTip.text = "新版本下载中..."
                    }
                    AppUpdateStatus.CANCEL -> {
                        tvSettingActivityUpdateTip.text = "下载被取消"
                    }
                    AppUpdateStatus.TO_BE_INSTALLED -> {
                        tvSettingActivityUpdateTip.text = "待安装"
                        if (selfUpdateCheck) appUpdateHelper.installUpdate(this@SettingActivity)
                    }
                    AppUpdateStatus.ERROR -> {
                        tvSettingActivityUpdateTip.text = "更新失败"
                        if (selfUpdateCheck) "获取更新失败！".showToast()
                    }
                    else -> return@Observer
                }
            })
        }

        mBinding.rlSettingActivityUpdate.setOnClickListener {
            selfUpdateCheck = true
            when (appUpdateHelper.getUpdateStatus().value) {
                AppUpdateStatus.DOWNLOADING -> {
                    "正在下载新版本，下拉可以查看进度".showToast()
                }
//                AppUpdateStatus.CANCEL -> {
//                    appUpdateService.noticeUpdate(this)
//                }
                AppUpdateStatus.CHECKING -> {
                    "已在检查，请稍等...".showToast()
                }
                AppUpdateStatus.TO_BE_INSTALLED -> {
                    appUpdateHelper.installUpdate(this)
                }
                else -> appUpdateHelper.checkUpdate()
            }
        }

        mBinding.rlSettingActivityUpdateServer.setOnClickListener {
            val builder: AlertDialog.Builder = AlertDialog.Builder(this)
            builder.setTitle(R.string.check_update_server)
            builder.setIcon(R.drawable.ic_storage_main_color_2_24)
            builder.setSingleChoiceItems(
                AppUpdateHelper.serverName, appUpdateHelper.getUpdateServer().value ?: 0
            ) { dialog, which ->
                if (which == 1)
                    "Gitee有请求次数的限制，可能会更新失败！\n由于第三方下载库存在BUG，通过Gitee服务器会下载失败。因此，只能通过浏览器下载"
                        .showToast(Toast.LENGTH_LONG)
                appUpdateHelper.setUpdateServer(which)
                dialog.dismiss()
            }
            builder.create().show()
        }

        initNightMode()
    }

    private fun initNightMode() {
        mBinding.run {
            if (isNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
                tvSettingActivityNightModeInfo.text = getString(R.string.night)
                switchSettingActivityNightMode.isChecked = true
            } else {
                tvSettingActivityNightModeInfo.text = getString(R.string.daytime)
                switchSettingActivityNightMode.isChecked = false
            }
            if (getNightMode() == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
                tvSettingActivityNightModeInfo.text = getString(R.string.follow_system)
                switchSettingActivityNightMode.isEnabled = false
                cbSettingActivityNightModeFollowSystem.isChecked = true
            } else {
                cbSettingActivityNightModeFollowSystem.isChecked = false
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                cbSettingActivityNightModeFollowSystem.isEnabled = true
                cbSettingActivityNightModeFollowSystem.setOnCheckedChangeListener { buttonView, isChecked ->
                    switchSettingActivityNightMode.isEnabled = !isChecked
                    tvSettingActivityNightModeInfo.text =
                        if (isChecked) setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                        else setNightMode(isNightMode())
                }
            } else {
                cbSettingActivityNightModeFollowSystem.gone()
                cbSettingActivityNightModeFollowSystem.isEnabled = false
            }

            switchSettingActivityNightMode.setOnCheckedChangeListener { buttonView, isChecked ->
                tvSettingActivityNightModeInfo.text =
                    if (isChecked) setNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                    else setNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
        }
    }

    override fun getBinding(): ActivitySettingBinding =
        ActivitySettingBinding.inflate(layoutInflater)
}
